package cn.shiva.jwt.interceptor;

import cn.shiva.jwt.basic.IgnoreJwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author shiva   2021/11/13 16:23
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String jwt = request.getHeader("Authorization");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有 IgnoreJwt 注释，有则跳过认证
        if (method.isAnnotationPresent(IgnoreJwt.class)) {
            IgnoreJwt ignoreJwt = method.getAnnotation(IgnoreJwt.class);
            if (ignoreJwt.ignored()) {
                return true;
            }
        }

        // 省略其他验证，直接拿 jwt
        Claims claims = Jwts.parser().setSigningKey("S@&op@!@.S5!)(@{").parseClaimsJws(jwt).getBody();
        //放入attribute以便后面调用
        request.setAttribute("claims", claims);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
